package async.callback;

import com.google.common.base.Stopwatch;
import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author jiangwenzhi
 */
public class TestCompletionService {

    public final static ExecutorService executorService = new ThreadPoolExecutor(5, 5,
            60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(32));


    public static Integer task01(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task01");
        return 0;
    }
    public static Integer task02(){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task02");
        return 0;
    }
    public static Integer task03(){
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task03");
        return 0;
    }

    @Test
    public void test01() throws InterruptedException, ExecutionException {
        CompletionService<Integer> completionSearchService = new ExecutorCompletionService<>(executorService);
        completionSearchService.submit(TestCompletionService::task01);
        completionSearchService.submit(TestCompletionService::task02);
        completionSearchService.submit(TestCompletionService::task03);

        Stopwatch started = Stopwatch.createStarted();
        for (int i = 0; i < 3; i++) {
            completionSearchService.take().get();
        }
//        TimeUnit.SECONDS.sleep(3);
        System.out.println("end cost" + started.elapsed().toString());
    }
}
